package com.wn.controller;

import com.wn.common.util.JwtUtil;
import com.wn.model.entity.China;
import com.wn.model.vo.AddressRequest;
import com.wn.model.vo.AddressVo;
import com.wn.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/address")
@Api(tags = "收货地址模块")
public class AddressController {
    @Autowired
    private AddressService addressService;
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 通过用户id获取当前用户的收货地址
     */
    @GetMapping("/findAddress")
    @ApiOperation("获取当前用户的收货地址")
    public ResponseEntity<List<AddressVo>> findAddress(@RequestHeader(name = "Authorization", required = false) String token) {
        //获取当前登录用户的id
        String userId = jwtUtil.getValue(token, "userId");
        //获取当前用户的地址列表
        List<AddressVo> list = addressService.findByUserId(Long.parseLong(userId));
        return ResponseEntity.ok(list);
    }

    @GetMapping("/getAllProvince")
    @ApiOperation("获取所有省份")
    public ResponseEntity<List<China>> getAllProvince() {
        List<China> list = addressService.getAllProvince();
        return ResponseEntity.ok(list);
    }

    /**
     * 根据省份id，查询城市
     */
    @GetMapping("/getAllCities")
    @ApiOperation("根据省份id，查询城市")
    @ApiImplicitParam(name = "provinceId", value = "省份id", required = true, dataType = "Integer")
    public ResponseEntity<List<China>> getAllCities(Integer provinceId) {

        List<China> list = addressService.getAllCities(provinceId);
        return ResponseEntity.ok(list);
    }

    /**
     * 根据省份id，查询城市
     */
    @GetMapping("/getAllDistricts")
    @ApiOperation("根据城市id，查询区/县")
    @ApiImplicitParam(name = "cityId", value = "城市id", required = true, dataType = "Integer")
    public ResponseEntity<List<China>> getAllDistricts(Integer cityId) {
        List<China> list = addressService.getAllDistricts(cityId);
        return ResponseEntity.ok(list);
    }

    /**
     * 保存地址
     */
    @PostMapping("/save")
    @ApiOperation("保存地址")
    public ResponseEntity save(@RequestBody AddressRequest addressRequest, @RequestHeader("Authorization") String token) {
        // 获取当前登录的用户id
        String userId = jwtUtil.getValue(token, "userId");
        addressService.addAddress(addressRequest, Long.valueOf(userId));
        return ResponseEntity.ok().build();
    }
}